from django.shortcuts import render
from django.views import View
from users.models import Address
from goods.models import SKU
from django.http import HttpResponseForbidden, JsonResponse , HttpResponse
from django_redis import get_redis_connection
import json
from orders.models import OrderInfo
import time
from django.db import transaction
from orders.models import *
# 订单视图
from utils.response_code import RETCODE

# 订单视图
class SettlementView(View):
    def get(self , request):
        user = request.user
        try:
            addresses = Address.objects.filter(user=user , is_delete=False)
        except Exception:
            addresses = None
            HttpResponseForbidden('用户数据有误')

        redis_conn = get_redis_connection('carts')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        redis_selected = redis_conn.smembers('selected_%s' % user.id)

        # 从redis 数据库中拿到的数据是二进制
        skus_dict = {}
        for skus_id in redis_selected:
            skus_dict[int(skus_id)] = int(redis_cart[skus_id])

        sku_id_list = skus_dict.keys()
        sku_object = SKU.objects.filter(id__in=sku_id_list)

        # 获取总件数和总价格
        total_number = 0
        total_amount = 0

        for sku in sku_object:
            sku.count = skus_dict[sku.id]
            sku.amount = sku.count * sku.price
            total_number += sku.count
            total_amount += sku.amount
        # 运费
        freight = 20

        context = {
            'addresses': addresses,
            'skus': sku_object,
            'total_amount': total_amount,
            'total_number': total_number,
            'freight': freight,
            'payment_amount': total_amount + freight
        }

        return render(request , 'place_order.html' , context=context)

# 提交订单
class OrderCommentView(View):
    def post(self , request):
        response = json.loads(request.body.decode())
        address_id = response['address_id']
        pay_method = response['pay_method']
        print(address_id)

        # 校验数据
        try:
            address_object = Address.objects.get(id=address_id)
        except Exception:
            return HttpResponseForbidden("地址信息有误")

        if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'],OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:
            return HttpResponseForbidden("支付方式有误")

        # 创建订单ID
        user = request.user
        current_time = str(time.time_ns())
        order_id = current_time + str(user.id)

        # 创建事务
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:

                if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY']:
                    status = OrderInfo.ORDER_STATUS_ENUM['UNPAID']
                else:
                    status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']

                order = OrderInfo.objects.create(
                    order_id = order_id,
                    user = user,
                    address=address_object,
                    total_count=0,
                    total_amount=0,
                    freight=20,
                    pay_method = pay_method,
                    status=status

                )
                redis_conn = get_redis_connection('carts')
                redis_cart = redis_conn.hgetall('cart_%s' % user.id)
                redis_selected = redis_conn.smembers('selected_%s' % user.id)

                cart_dict = {}
                for sku_id in redis_selected:
                    cart_dict[int(sku_id)] = int(redis_cart[sku_id])

                skus = SKU.objects.filter(id__in=cart_dict.keys())
                for sku in skus:

                    # 获取到该商品购买件数
                    sku_count = cart_dict[sku.id]

                    # 获取商品的销量和库存
                    origin_stock = sku.stock
                    origin_sales = sku.sales

                    # 判断商品的库存是否足够
                    if sku_count > origin_stock:
                        transaction.savepoint_rollback(save_id)
                        return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '商品库存不足'})
                    print(2)

                    # 对库存进行减少 ， 销量进行增加
                    sku.stock -= sku_count
                    sku.sales += sku_count
                    sku.save()

                    # 保存商品订单信息
                    OrderGoods.objects.create(
                        order=order,
                        sku=sku,
                        count=sku_count,
                        price=sku.price
                    )


                    # 计算单间商品的购买数量和总金额
                    order.total_count += sku_count
                    order.total_amount += sku_count * sku.price



                # 对总金额加入运费
                order.total_amount += order.freight
                order.save()
                print(3)





            except Exception:
                print(Exception)
                transaction.savepoint_commit(save_id)
                return HttpResponseForbidden('提交数据有误')

        transaction.savepoint_commit(save_id)
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'order_id': order_id})


class OrderSeccessView(View):
    def get(self , request):
        print(request.GET)
        order_id = request.GET.get('order_id')
        payment_amount = request.GET.get('payment_amount')
        pay_method = request.GET.get('pay_method')

        context = {
            'order_id':order_id,
            'payment_amount':payment_amount,
        }




        return render(request , 'order_success.html' ,context=context)










